#include "math.h"

	Ray::Ray()
	{
	}

	Ray::Ray(D3DXVECTOR3 p,D3DXVECTOR3 d)
		:m_pos(p)
	{
		D3DXVec3Normalize(&m_direction,&d);
	}

	Ray::~Ray()
	{
	}
	
	bool Ray::Intersects(const Plane& p, D3DXVECTOR3* pt)
	{
		float tmp=D3DXVec3Dot(&p.m_n,&m_direction);
		if(tmp<0.00001f&&tmp>0.00001f)
			return false;
		float t=-(p.m_d+D3DXVec3Dot(&p.m_n,&m_pos))/tmp;
		*pt=m_pos+t*m_direction;
		return true;
	}

	bool Ray::Intersects(const AABB& aabb,float* t)
	{
		D3DXVECTOR3 dirfrac;
		// r.dir is unit direction vector of ray
		dirfrac.x = 1.0f / m_direction.x;
		dirfrac.y = 1.0f / m_direction.y;
		dirfrac.z = 1.0f / m_direction.z;
		// lb is the corner of AABB with minimal coordinates - left bottom, rt is maximal corner
		// r.org is origin of ray
		float t1 = (aabb.m_min.x - m_pos.x)*dirfrac.x;
		float t2 = (aabb.m_max.x - m_pos.x)*dirfrac.x;
		float t3 = (aabb.m_min.y - m_pos.y)*dirfrac.y;
		float t4 = (aabb.m_max.y - m_pos.y)*dirfrac.y;
		float t5 = (aabb.m_min.z - m_pos.z)*dirfrac.z;
		float t6 = (aabb.m_max.z - m_pos.z)*dirfrac.z;

		float tmin = max(max(min(t1, t2), min(t3, t4)), min(t5, t6));
		float tmax = min(min(max(t1, t2), max(t3, t4)), max(t5, t6));

		// if tmax < 0, ray (line) is intersecting AABB, but whole AABB is behing us
		if (tmax < 0)
		{
			*t = tmax;
			return false;
		}

		// if tmin > tmax, ray doesn't intersect AABB
		if (tmin > tmax)
		{
			*t = tmax;
			return false;
		}

		*t = tmin;
		return true;
	}

	/*AABB::AABB(void)
	{
	}*/

	AABB::AABB(D3DXVECTOR3 min,D3DXVECTOR3 max,float r)
		:m_min(min),
		m_max(max)
	{
		CreateCoord();
		//m_radius=r;
	}

	AABB::AABB(D3DXVECTOR2 p)
	{
		m_min=D3DXVECTOR3(0,0,0);
		m_max=D3DXVECTOR3(p.x,10,p.y);
		m_center=D3DXVECTOR3(p.x/2,5,p.y/2);
	}

	AABB::~AABB(void)
	{
	}

	void AABB::CreateCoord()
	{
		m_pos[0]=m_min;
		m_pos[1]=D3DXVECTOR3(m_max.x,m_min.y,m_min.z);
		m_pos[2]=D3DXVECTOR3(m_max.x,m_min.y,m_max.z);
		m_pos[3]=D3DXVECTOR3(m_min.x,m_min.y,m_max.z);
		m_pos[4]=D3DXVECTOR3(m_min.x,m_max.y,m_min.z);
		m_pos[5]=D3DXVECTOR3(m_max.x,m_max.y,m_min.z);
		m_pos[6]=m_max;
		m_pos[7]=D3DXVECTOR3(m_min.x,m_max.y,m_max.z);
	}

	AABB* AABB::TransToView(D3DXMATRIX& m)
	{
		D3DXMATRIX tmp;
		//D3DXMatrixMultiply(&tmp,o
		return NULL;
	}

	Plane::Plane(D3DXVECTOR3 n,float d)
		:m_n(n),
		m_d(d)
	{
	}

	Plane::~Plane()
	{
	}
